// 音乐播放器控制功能

// 使用已在app.js中声明的audio变量
const playBtn = document.getElementById('play-btn');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const progressBar = document.querySelector('.progress-bar');
const progress = document.getElementById('progress');
const currentTimeElement = document.getElementById('current-time');
const durationElement = document.getElementById('duration');
const volumeBar = document.querySelector('.volume-bar');
const volumeProgress = document.getElementById('volume-progress');

// 初始化播放器控制
function initPlayer() {
    // 添加事件监听器
    playBtn.addEventListener('click', window.app.togglePlay);
    prevBtn.addEventListener('click', window.app.playPrevious);
    nextBtn.addEventListener('click', window.app.playNext);
    audio.addEventListener('timeupdate', updateProgress);
    audio.addEventListener('loadedmetadata', updateDuration);
    progressBar.addEventListener('click', setProgress);
    volumeBar.addEventListener('click', setVolume);
    
    // 初始化音量
    audio.volume = 0.8; // 默认音量80%
    volumeProgress.style.width = '80%';
}

// 更新进度条 - 使用requestAnimationFrame优化性能
let lastUpdateTime = 0;
function updateProgress() {
    // 使用requestAnimationFrame确保动画流畅
    requestAnimationFrame(() => {
        if (audio.duration) {
            const progressPercent = (audio.currentTime / audio.duration) * 100;
            
            // 限制更新频率，避免过度渲染
            const currentTime = Date.now();
            if (currentTime - lastUpdateTime > 16 || Math.abs(parseFloat(progress.style.width) - progressPercent) > 0.5) {
                progress.style.width = progressPercent + '%';
                
                // 更新当前时间显示
                currentTimeElement.textContent = formatTime(audio.currentTime);
                lastUpdateTime = currentTime;
            }
            
            // 添加调试日志，监控音频时间更新
            console.log(`音频时间: ${audio.currentTime.toFixed(2)}s, 持续时间: ${audio.duration.toFixed(2)}s`);
            
            // 更新歌词显示 - 使用重构后的window.lyrics对象
            if (typeof window.lyrics !== 'undefined' && window.lyrics.updateLyricsDisplay) {
                console.log('调用 window.lyrics.updateLyricsDisplay 函数');
                window.lyrics.updateLyricsDisplay(audio.currentTime);
            } else {
                console.warn('未找到歌词更新函数');
                console.log('当前window对象中的可用属性: ' + Object.keys(window).filter(key => key.toLowerCase().includes('lyric')).join(', '));
            }
        }
    });
}

// 更新歌曲总时长
function updateDuration() {
    durationElement.textContent = formatTime(audio.duration);
}

// 设置播放进度 - 添加平滑动画效果
function setProgress(e) {
    const width = this.clientWidth;
    const clickX = e.offsetX;
    const duration = audio.duration;
    
    // 立即更新进度条视觉效果
    const progressPercent = (clickX / width) * 100;
    progress.style.width = progressPercent + '%';
    
    // 添加短暂延迟后再更新实际播放位置
    // 这可以让用户看到进度条移动后再跳转到新位置
    setTimeout(() => {
        audio.currentTime = (clickX / width) * duration;
    }, 100);
}

// 设置音量 - 优化交互体验
let isDraggingVolume = false;

// 添加鼠标按下事件监听
volumeBar.addEventListener('mousedown', () => {
    isDraggingVolume = true;
});

// 添加鼠标松开事件监听
window.addEventListener('mouseup', () => {
    if (isDraggingVolume) {
        isDraggingVolume = false;
    }
});

// 添加鼠标移动事件监听
window.addEventListener('mousemove', (e) => {
    if (isDraggingVolume) {
        // 获取volumeBar元素的位置
        const rect = volumeBar.getBoundingClientRect();
        // 计算相对于volumeBar的点击位置
        const clickX = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
        const volume = clickX / rect.width;
        
        audio.volume = volume;
        volumeProgress.style.width = (volume * 100) + '%';
    }
});

function setVolume(e) {
    const width = this.clientWidth;
    const clickX = e.offsetX;
    const volume = clickX / width;
    
    audio.volume = volume;
    volumeProgress.style.width = (volume * 100) + '%';
}

// 格式化时间（将秒转换为分:秒格式）
function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
}

// 导出公共方法
window.player = {
    init: initPlayer,
    formatTime: formatTime
};

// 页面加载完成后初始化播放器控制
window.addEventListener('DOMContentLoaded', player.init);